package com.lingnan.interceptor;


import feign.RequestInterceptor;
import feign.RequestTemplate;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Objects;


/**
 * @author hehangjie
 * @date 2025/06/27
 */
@Component
@Slf4j
public class FeignRequestInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        try {
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (Objects.nonNull(requestAttributes)) {
                HttpServletRequest request = requestAttributes.getRequest();
                if (Objects.nonNull(request)) {
                    String loginId = request.getHeader("loginId");
                    if (StringUtils.isNotBlank(loginId)) {
                        log.info("feign请求拦截器拦截到请求，请求头信息为：{}", loginId);
                        requestTemplate.header("loginId", loginId);
                    }
                }
            }
        } catch (Exception e) {
            log.error("Feign请求拦截器处理异常", e);
        }
    }

}
